//
//  CubeViewController.m
//  CoreAnimationDemo
//
//  Created by 王亮 on 2017/8/9.
//  Copyright © 2017年 王亮. All rights reserved.
//

#import "CubeViewController.h"
#import <GLKit/GLKit.h>

#define LIGHT_DIRECTION 0, 1, -0.5
#define AMBIENT_LIGHT 0.5

@interface CubeViewController ()

@property (nonatomic, strong)NSMutableArray *faces;
@property (nonatomic, strong)UIView *containerView;

@end

@implementation CubeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.faces = [NSMutableArray arrayWithCapacity:0];
    NSInteger num = 6;
    CGSize faceSize = CGSizeMake(100, 100);
    for (int i = 0; i < num; i++) {
        UIView *face = [[UIView alloc] initWithFrame:CGRectMake(0, 0, faceSize.width, faceSize.height)];
        face.backgroundColor = [UIColor whiteColor];
        
        if (i == 4) {
            //add button
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(0, 0, 50, 50);
            btn.backgroundColor = [UIColor blueColor];
            btn.center = CGPointMake(faceSize.width/2.0, faceSize.height/2.0);
            [btn setTitle:@"4" forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            [btn addTarget:self action:@selector(clickFace4) forControlEvents:UIControlEventTouchUpInside];
            btn.titleLabel.font = [UIFont systemFontOfSize:40];
            [face addSubview:btn];
            
            face.userInteractionEnabled = YES;
        } else {
            UILabel *label = [[UILabel alloc] init];
            label.frame = CGRectMake(0, 0, 50, 50);
            label.center = CGPointMake(faceSize.width/2.0, faceSize.height/2.0);
            label.text = [NSString stringWithFormat:@"%@",@(i)];
            label.font = [UIFont systemFontOfSize:40];
            label.textColor = [UIColor colorWithRed:(arc4random()%256)/255.0 green:(arc4random()%256)/255.0 blue:(arc4random()%256)/255.0 alpha:1.0];
            label.textAlignment = NSTextAlignmentCenter;
            [face addSubview:label];
            
            face.userInteractionEnabled = NO;
        }
        [self.faces addObject:face];
    }
    
    self.containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width)];
    self.containerView.backgroundColor = [UIColor grayColor];
    self.containerView.center = self.view.center;
    self.containerView.userInteractionEnabled = YES;
    [self.view addSubview:self.containerView];
    
    //add face
    CATransform3D perspective = CATransform3DIdentity;
    perspective.m34 = -1.0/500.0;
    perspective = CATransform3DRotate(perspective, -M_PI_4, 1, 0, 0);
    perspective = CATransform3DRotate(perspective, -M_PI_4, 0, 1, 0);
    self.containerView.layer.sublayerTransform = perspective;
    //add face1
    CATransform3D transform = CATransform3DMakeTranslation(0, 0, faceSize.width/2.0);
    [self addFace:0 withTransform:transform];
    //add face2
    transform = CATransform3DMakeTranslation(faceSize.width/2.0, 0, 0);
    transform = CATransform3DRotate(transform, -M_PI_2, 0, 1, 0);
    [self addFace:1 withTransform:transform];
    //add face3
    transform = CATransform3DMakeTranslation(0, 0, -faceSize.width/2.0);
    [self addFace:2 withTransform:transform];
    //add face4
    transform = CATransform3DMakeTranslation(-faceSize.width/2.0, 0, 0);
    transform = CATransform3DRotate(transform, M_PI_2, 0, 1, 0);
    [self addFace:3 withTransform:transform];
    //add face5
    transform = CATransform3DMakeTranslation(0, -faceSize.width/2.0, 0);
    transform = CATransform3DRotate(transform, M_PI_2, 1, 0, 0);
    [self addFace:4 withTransform:transform];
    //add face6
    transform = CATransform3DMakeTranslation(0, faceSize.width/2.0, 0);
    transform = CATransform3DRotate(transform, -M_PI_2, 1, 0, 0);
    [self addFace:5 withTransform:transform];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addFace:(NSInteger)index withTransform:(CATransform3D)transform {
    UIView *face = self.faces[index];
    [self.containerView addSubview:face];
    
    CGSize contentSize = self.containerView.frame.size;
    face.center = CGPointMake(contentSize.width/2.0, contentSize.height/2.0);
    
    face.layer.transform = transform;
    
    [self applyLightingToFace:face.layer];
}


- (void)applyLightingToFace:(CALayer *)face
{
    //add lighting layer
    CALayer *layer = [CALayer layer];
    layer.frame = face.bounds;
    [face addSublayer:layer];
    
    //convert the face transform to matrix
    //(GLKMatrix4 has the same structure as CATransform3D)
    //译者注：GLKMatrix4和CATransform3D内存结构一致，但坐标类型有长度区别，所以理论上应该做一次CGFloat到CGCGFloat的转换，感谢[@zihuyishi](https://github.com/zihuyishi)同学~
    CATransform3D transform = face.transform;\
    GLKMatrix4 matrix4 = GLKMatrix4Make((float)transform.m11, (float)transform.m12, (float)transform.m13, (float)transform.m14, (float)transform.m21, (float)transform.m22, (float)transform.m23, (float)transform.m24, (float)transform.m31, (float)transform.m32, (float)transform.m33, (float)transform.m34, (float)transform.m41, (float)transform.m42, (float)transform.m43, (float)transform.m44);
    GLKMatrix3 matrix3 = GLKMatrix4GetMatrix3(matrix4);
    //get face normal
    GLKVector3 normal = GLKVector3Make(0, 0, 1);
    normal = GLKMatrix3MultiplyVector3(matrix3, normal);
    normal = GLKVector3Normalize(normal);
    //get dot product with light direction
    GLKVector3 light = GLKVector3Normalize(GLKVector3Make(LIGHT_DIRECTION));
    CGFloat dotProduct = GLKVector3DotProduct(light, normal);
    //set lighting layer opacity
    CGFloat shadow = 1 + dotProduct - AMBIENT_LIGHT;
    UIColor *color = [UIColor colorWithWhite:0 alpha:shadow];
    layer.backgroundColor = color.CGColor;
}

- (void)clickFace4 {
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"hi" message:@"hi" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertVc dismissViewControllerAnimated:YES completion:nil];
    }];
    [alertVc addAction:action1];
    [self presentViewController:alertVc animated:YES completion:nil];
}
@end
